package com.ruoyi.system.service.impl.ingredientsServiceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.Validate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserMsg;
import com.ruoyi.system.domain.ingredients.PartIngredients;
import com.ruoyi.system.domain.ingredients.PartIngredientsDetail;
import com.ruoyi.system.domain.ingredients.PartIngredientsException;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserMsgMapper;
import com.ruoyi.system.mapper.ingredients.PartIngredientsDetailMapper;
import com.ruoyi.system.mapper.ingredients.PartIngredientsExceptionMapper;
import com.ruoyi.system.mapper.ingredients.PartIngredientsMapper;
import com.ruoyi.system.service.ingredientsService.IPartIngredientsExceptionService;

/**
 * 辅料异常记录Service业务层处理
 * 
 * @author ljx
 * @date 2020-07-01
 */
@Service
public class PartIngredientsExceptionServiceImpl implements IPartIngredientsExceptionService
{
    @Resource
    private PartIngredientsExceptionMapper partIngredientsExceptionMapper;
    @Resource
    private PartIngredientsMapper partIngredientsMapper;
    @Resource
    private PartIngredientsDetailMapper partIngredientsDetailMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserMsgMapper sysUserMsgMapper;

    /**
     * 查询辅料异常记录
     * 
     * @param id 辅料异常记录ID
     * @return 辅料异常记录
     */
    @Override
    public PartIngredientsException selectPartIngredientsExceptionById(Long id)
    {
        return partIngredientsExceptionMapper.getObjectById(id);
    }

    /**
     * 查询辅料异常记录列表
     * 
     * @param partIngredientsException 辅料异常记录
     * @return 辅料异常记录
     */
    @Override
    public List<PartIngredientsException> selectPartIngredientsExceptionList(PartIngredientsException partIngredientsException)
    {
        return partIngredientsExceptionMapper.getList(partIngredientsException);
    }

    /**
     * 新增辅料异常记录
     * 
     * @param partIngredientsException 辅料异常记录
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult insertPartIngredientsException(PartIngredientsException partIngredientsException)
    {
    	Long partId = partIngredientsException.getPartId();
    	Long changeValue = partIngredientsException.getChangeValue();
    	if (changeValue.longValue() == 0l) {
			return AjaxResult.error("异常数量不能为0");
		}
    	PartIngredients selectPartIngredientsById = partIngredientsMapper.selectPartIngredientsById(partId);
    	long nowSt = selectPartIngredientsById.getInventory().longValue()+changeValue.longValue();
    	if (nowSt < 0 ) {
			return AjaxResult.error("最多就有"+selectPartIngredientsById.getInventory()+"库存");
		}
    	
    	
        partIngredientsException.setCreateTime(DateUtils.getNowDate());
        changeIngredients(partIngredientsException);
        
        
        PartIngredientsDetail partIngredientsDetail = new PartIngredientsDetail();
        partIngredientsDetail.setPartId(partId);
        partIngredientsDetail.setCreateTime(new Date());
        partIngredientsDetail.setCreateBy(partIngredientsException.getCreateBy());
        partIngredientsDetail.setChangeValue(changeValue );
        //加库存记录
        if (changeValue.compareTo(0l) > 0) {
			//入库
        	partIngredientsDetail.setType(2);
		}else {
			//出库
			partIngredientsDetail.setType(1);
		}
        selectPartIngredientsById.setInventory(nowSt);
        
        List<SysUser> send = new ArrayList<SysUser>();
        if (nowSt <= 20) {
			//发消息来出来
        	 send = send("#"+selectPartIngredientsById.getName()+"##"+selectPartIngredientsById.getSubName()+"#库存数量为"+nowSt+"#请尽快补货");
		}
        
        partIngredientsMapper.updatePartIngredients(selectPartIngredientsById);
        partIngredientsDetail.setReceiver(partIngredientsException.getCreateBy());
        
        partIngredientsDetailMapper.insertPartIngredientsDetail(partIngredientsDetail);
        
        partIngredientsExceptionMapper.insertPartIngredientsException(partIngredientsException);
        return AjaxResult.success( send );
    }
    
    public List<SysUser> send(String message){
		List<SysUser> selectAllocatedList = sysUserMapper.selectAllUserList();
		for (SysUser sysUser : selectAllocatedList) {
			SysUserMsg sysUserMsg = new SysUserMsg();
			sysUserMsg.setUserId(sysUser.getUserId());
			sysUserMsg.setContent(message);
			sysUserMsg.setIsRead("1");
			sysUserMsg.setCreateTime(new Date());
			sysUserMsgMapper.insertSysUserMsg(sysUserMsg);
		}
		return selectAllocatedList;
		
    }

    /**
     * 修改辅料异常记录
     * 
     * @param partIngredientsException 辅料异常记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updatePartIngredientsException(PartIngredientsException partIngredientsException)
    {
        partIngredientsException.setUpdateTime(DateUtils.getNowDate());
        //获取历史异常记录
        PartIngredientsException part = partIngredientsExceptionMapper.selectPartIngredientsExceptionById(partIngredientsException.getId());
        //计算修改值，修改辅料库存数量
        Long change = partIngredientsException.getChangeValue() - part.getChangeValue();
        part.setChangeValue(change);
        if(change.intValue()!=0 && changeIngredients(part) == 0){
            return 0;
        }
        //修改异常辅料数据
        return partIngredientsExceptionMapper.updatePartIngredientsException(partIngredientsException);
    }

    /**
     * 删除辅料异常记录对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult deletePartIngredientsExceptionByIds(String ids) {
        String[] strings = Convert.toStrArray(ids);
        Map<String, Object> map = new HashMap<>();
        for (String id : strings) {
        	PartIngredientsException selectPartIngredientsExceptionById = partIngredientsExceptionMapper.selectPartIngredientsExceptionById(new Long(id));
        	Long changeValue = selectPartIngredientsExceptionById.getChangeValue();
        	Long partId = selectPartIngredientsExceptionById.getPartId();
        	
           	PartIngredients selectPartIngredientsById = partIngredientsMapper.selectPartIngredientsById(partId);
           	Long inventory = selectPartIngredientsById.getInventory();
           	long nowSt = 0l;
           	
            PartIngredientsDetail partIngredientsDetail = new PartIngredientsDetail();
            partIngredientsDetail.setPartId(partId);
            partIngredientsDetail.setCreateTime(new Date());
//            partIngredientsDetail.setCreateBy(partIngredientsException.getCreateBy());
            partIngredientsDetail.setChangeValue(changeValue );
            
           	if (changeValue.compareTo(0l) < 0) {
				//出库
           		nowSt = inventory+changeValue;
           		partIngredientsDetail.setType(2);
			}else{
				//入库
				nowSt = inventory-changeValue;
				partIngredientsDetail.setType(1);
				if (nowSt < 0l) {
					Validate.isTrue(false,selectPartIngredientsById.getName()+"异常数量删除后库存小于0了");
				}
			}
           	partIngredientsDetailMapper.insertPartIngredientsDetail(partIngredientsDetail);
           	selectPartIngredientsById.setInventory(nowSt);
            List<SysUser> send = new ArrayList<SysUser>();
            if (nowSt <= 20) {
    			//发消息来出来
            	 send = send("#"+selectPartIngredientsById.getName()+"##"+selectPartIngredientsById.getSubName()+"#库存数量为"+nowSt+"#请尽快补货");
            	 for (SysUser sysUser : send) {
            		 map.put(sysUser.getUserId().toString(), sysUser.getUserId());
				}
    		}
            
           	partIngredientsMapper.updatePartIngredients(selectPartIngredientsById);
        	
           	partIngredientsExceptionMapper.deletePartIngredientsExceptionById(Long.valueOf(id));
        }
        return AjaxResult.success(map);
    }

    /**
     * 删除辅料异常记录信息
     * 
     * @param id 辅料异常记录ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePartIngredientsExceptionById(Long id)
    {
        //获取历史异常记录
        PartIngredientsException part = partIngredientsExceptionMapper.selectPartIngredientsExceptionById(id);
        part.setChangeValue(part.getChangeValue()*-1);
        changeIngredients(part);
        return partIngredientsExceptionMapper.deletePartIngredientsExceptionById(id);
    }

    int changeIngredients(PartIngredientsException part){
        if(part.getChangeValue()==null || part.getPartId()==null){
            return 0;
        }
        return partIngredientsMapper.updateInventoryFromExc(part);
    }
}
